package com.jerry.consumer.controller;

import com.jerry.common.bean.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/shop/product")
public class ProductController {
	
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private DiscoveryClient discoveryClient;

	@Value("${provider.productUrl}")
	private String productUrl;
	
	//查询产品列表
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	public List<Product> getProductList() {
		List<Product> productList = restTemplate.getForObject(this.productUrl + "/product/list", List.class);
		return productList;
	}
		
	//根据id查询产品
	@GetMapping("/get/{id}")
	public Product getProduct(@PathVariable("id") Long id) {
		return restTemplate.getForObject(this.productUrl + "/product/get/" + id, Product.class);
	}

	//增加一个产品
	@GetMapping("/add")
	public boolean addProduct(Product product) {
		return restTemplate.postForObject(this.productUrl + "/product/add", product, Boolean.class);
	}
	
	//增加一个产品
	@GetMapping("/update")
	public boolean updateProduct(Product product) {
		return restTemplate.postForObject(this.productUrl + "/product/update", product, Boolean.class);
	}
	
	//删除一个产品
	@GetMapping("/delete/{id}")
	public void deleteProduct(@PathVariable("id") Long id) {
		restTemplate.delete(this.productUrl + "/product/delete/"+id);
	}

	//查询provider-product的实例信息
	@GetMapping("/productInstance")
	public List<ServiceInstance> productInstance() {
		return this.discoveryClient.getInstances("provider-product");
	}
	
	
}
